package top.jacktgq.hsp.netty.heartbeat;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;

import java.util.concurrent.TimeUnit;

/**
 * @Author CandyWall
 * @Date 2020/11/12--22:19
 * @Description netty服务器：测试心跳机制
 */
public class NettyServer {
    public static void main(String[] args) {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                /*.option(ChannelOption.SO_BACKLOG, 100)
                .childOption(ChannelOption.SO_KEEPALIVE, true)*/
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        //获取Pipeline
                        ChannelPipeline pipeline = ch.pipeline();
                        //加入一个netty提供的IdleStateHandler
                        //说明：
                        //1、IdleStateHandler 是netty提供的处理空闲状态的处理器
                        // long readeridleTime  ：表示多长时间没有读，就会发送一个心跳检测包，检测是否还是连接的状态
                        // long writerIdleTime  ：表示多长时间没有写，就会发送一个心跳检测包，检测是否还是连接的状态
                        // long allIdleTime     ：表示多长时间没有读写，就会发送一个心跳检测包，检测是否还是连接的状态
                        //当IdleStateEvent触发后，就会传递给管道的下一个Handler去处理，通过调用（触发）下一个Handler的userEventTriggered，在方法中去处理（读空闲，写空闲，读写空闲）
                        pipeline.addLast(new IdleStateHandler(3, 5, 7, TimeUnit.SECONDS));
                        //加入一个对空闲检测进一步处理的Handler（自定义）
                        pipeline.addLast(new NettyServerHandler());
                    }
                });
        try {
            ChannelFuture channelFuture = bootstrap.bind(9999).sync();
            System.out.println("服务器启动成功...");
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
